#include "systemconfig.h"
#include <QDebug>
#include <QSysInfo>

#ifdef Q_OS_WIN
#include <windows.h>
#elif defined(Q_OS_MACOS) || defined(Q_OS_LINUX)
#include <sys/sysctl.h>
#include <unistd.h>
#endif

// ============================================================================
// SystemConfig 实现
// ============================================================================

int SystemConfig::calculateMaxPagesInMemory() const
{
    return ConfigStrategyCalculator::calculateMaxPagesForStrategy(memoryStrategy);
}

int SystemConfig::calculatePreloadRange() const
{
    return ConfigStrategyCalculator::calculatePreloadRangeForStrategy(memoryStrategy);
}

double SystemConfig::getProcessingDpi() const
{
    return ConfigStrategyCalculator::calculateDpiForQuality(processingQuality);
}

// === 字符串转换方法 ===
QString SystemConfig::memoryStrategyToString(MemoryStrategy strategy)
{
    switch (strategy) {
        case MemoryStrategy::PowerSaving: return "PowerSaving";
        case MemoryStrategy::Balanced: return "Balanced";
        case MemoryStrategy::HighPerformance: return "HighPerformance";
        case MemoryStrategy::Extreme: return "Extreme";
        default: return "Balanced";
    }
}

MemoryStrategy SystemConfig::memoryStrategyFromString(const QString& str)
{
    if (str == "PowerSaving") return MemoryStrategy::PowerSaving;
    if (str == "HighPerformance") return MemoryStrategy::HighPerformance;
    if (str == "Extreme") return MemoryStrategy::Extreme;
    return MemoryStrategy::Balanced; // 默认值
}

QString SystemConfig::processingQualityToString(ProcessingQuality quality)
{
    switch (quality) {
        case ProcessingQuality::Fast: return "Fast";
        case ProcessingQuality::Standard: return "Standard";
        case ProcessingQuality::High: return "High";
        case ProcessingQuality::Extreme: return "Extreme";
        default: return "High";
    }
}

ProcessingQuality SystemConfig::processingQualityFromString(const QString& str)
{
    if (str == "Fast") return ProcessingQuality::Fast;
    if (str == "Standard") return ProcessingQuality::Standard;
    if (str == "Extreme") return ProcessingQuality::Extreme;
    return ProcessingQuality::High; // 默认值
}

QString SystemConfig::layoutModeToString(LayoutMode mode)
{
    switch (mode) {
        case LayoutMode::SingleColumn: return "SingleColumn";
        case LayoutMode::TwoColumns: return "TwoColumns";
        case LayoutMode::ThreeColumns: return "ThreeColumns";
        default: return "SingleColumn";
    }
}

LayoutMode SystemConfig::layoutModeFromString(const QString& str)
{
    if (str == "TwoColumns") return LayoutMode::TwoColumns;
    if (str == "ThreeColumns") return LayoutMode::ThreeColumns;
    return LayoutMode::SingleColumn; // 默认值
}

// ============================================================================
// ConfigStrategyCalculator 实现
// ============================================================================

int ConfigStrategyCalculator::calculateMaxPagesForStrategy(MemoryStrategy strategy)
{
    qint64 availableMemoryMB = getAvailableMemoryMB();

    // 根据策略计算使用内存的百分比
    double memoryUsageRatio = 0.0;
    switch (strategy) {
        case MemoryStrategy::PowerSaving:
            memoryUsageRatio = 0.25;  // 25%
            break;
        case MemoryStrategy::Balanced:
            memoryUsageRatio = 0.45;  // 45%
            break;
        case MemoryStrategy::HighPerformance:
            memoryUsageRatio = 0.65;  // 65%
            break;
        case MemoryStrategy::Extreme:
            memoryUsageRatio = 0.80;  // 80%
            break;
    }

    // 估算每页占用内存（以A4 300DPI为基准，约3MB/页）
    const int avgMemoryPerPageMB = 3;
    qint64 targetMemoryMB = static_cast<qint64>(availableMemoryMB * memoryUsageRatio);
    int maxPages = static_cast<int>(targetMemoryMB / avgMemoryPerPageMB);

    // 设置合理的范围限制
    maxPages = qMax(10, qMin(maxPages, 500)); // 最小10页，最大500页


    return maxPages;
}

int ConfigStrategyCalculator::calculatePreloadRangeForStrategy(MemoryStrategy strategy)
{
    // 预加载范围与内存策略成正比
    switch (strategy) {
        case MemoryStrategy::PowerSaving: return 2;
        case MemoryStrategy::Balanced: return 5;
        case MemoryStrategy::HighPerformance: return 8;
        case MemoryStrategy::Extreme: return 15;
        default: return 5;
    }
}

double ConfigStrategyCalculator::calculateDpiForQuality(ProcessingQuality quality)
{
    switch (quality) {
        case ProcessingQuality::Fast: return 150.0;
        case ProcessingQuality::Standard: return 200.0;
        case ProcessingQuality::High: return 300.0;
        case ProcessingQuality::Extreme: return 600.0;
        default: return 300.0;
    }
}

QString ConfigStrategyCalculator::getQualityDescription(ProcessingQuality quality)
{
    switch (quality) {
        case ProcessingQuality::Fast:
            return "快速模式 (150 DPI) - 占用空间小，处理速度快";
        case ProcessingQuality::Standard:
            return "标准模式 (200 DPI) - 平衡质量和空间";
        case ProcessingQuality::High:
            return "高质量模式 (300 DPI) - 推荐设置，适合高分屏";
        case ProcessingQuality::Extreme:
            return "极致模式 (600 DPI) - 最高质量，占用空间大";
        default:
            return "高质量模式 (300 DPI)";
    }
}

QString ConfigStrategyCalculator::getMemoryStrategyDescription(MemoryStrategy strategy)
{
    qint64 availableMemoryMB = getAvailableMemoryMB();
    int maxPages = calculateMaxPagesForStrategy(strategy);
    int preloadRange = calculatePreloadRangeForStrategy(strategy);

    QString baseDesc;
    switch (strategy) {
        case MemoryStrategy::PowerSaving:
            baseDesc = "节能模式 - 最小内存占用，适合低配设备";
            break;
        case MemoryStrategy::Balanced:
            baseDesc = "平衡模式 - 性能与内存的最佳平衡";
            break;
        case MemoryStrategy::HighPerformance:
            baseDesc = "高性能模式 - 更好的响应速度";
            break;
        case MemoryStrategy::Extreme:
            baseDesc = "极致模式 - 最大化性能，需要充足内存";
            break;
        default:
            baseDesc = "平衡模式";
    }

    return QString("%1\n最大页数: %2, 预加载: %3页")
           .arg(baseDesc)
           .arg(maxPages)
           .arg(preloadRange);
}

// === 系统内存检测 ===
qint64 ConfigStrategyCalculator::getTotalSystemMemoryMB()
{
#ifdef Q_OS_WIN
    MEMORYSTATUSEX memInfo;
    memInfo.dwLength = sizeof(MEMORYSTATUSEX);
    GlobalMemoryStatusEx(&memInfo);
    return static_cast<qint64>(memInfo.ullTotalPhys / 1024 / 1024);
#elif defined(Q_OS_MACOS)
    int mib[2];
    mib[0] = CTL_HW;
    mib[1] = HW_MEMSIZE;
    int64_t physical_memory;
    size_t length = sizeof(int64_t);
    sysctl(mib, 2, &physical_memory, &length, NULL, 0);
    return static_cast<qint64>(physical_memory / 1024 / 1024);
#elif defined(Q_OS_LINUX)
    long pages = sysconf(_SC_PHYS_PAGES);
    long page_size = sysconf(_SC_PAGE_SIZE);
    return static_cast<qint64>((pages * page_size) / 1024 / 1024);
#else
    return 4096; // 默认假设4GB
#endif
}

qint64 ConfigStrategyCalculator::getAvailableMemoryMB()
{
#ifdef Q_OS_WIN
    MEMORYSTATUSEX memInfo;
    memInfo.dwLength = sizeof(MEMORYSTATUSEX);
    GlobalMemoryStatusEx(&memInfo);
    return static_cast<qint64>(memInfo.ullAvailPhys / 1024 / 1024);
#else
    // macOS和Linux上简化处理，使用总内存的70%作为可用内存
    return static_cast<qint64>(getTotalSystemMemoryMB() * 0.7);
#endif
}

bool ConfigStrategyCalculator::isMemoryStrategyRecommended(MemoryStrategy strategy)
{
    qint64 totalMemoryMB = getTotalSystemMemoryMB();

    switch (strategy) {
        case MemoryStrategy::PowerSaving:
            return totalMemoryMB < 4096;  // 4GB以下推荐节能模式
        case MemoryStrategy::Balanced:
            return totalMemoryMB >= 4096 && totalMemoryMB < 8192; // 4-8GB推荐平衡模式
        case MemoryStrategy::HighPerformance:
            return totalMemoryMB >= 8192 && totalMemoryMB < 16384; // 8-16GB推荐高性能
        case MemoryStrategy::Extreme:
            return totalMemoryMB >= 16384; // 16GB以上推荐极致模式
        default:
            return true;
    }
}